package core

import (
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"log"
	"reflect"
)

// config from file
type Config struct {
	//#excel路径
	XlsxSourcePath string `yaml:"xlsxSourcePath"`
	//json文字替换
	ReplaceFix string `yaml:"replaceFix"`
	Exports    struct {
		LUA  *ExportConfig `yaml:"lua"`
		CSV  *ExportConfig `yaml:"csv"`
		JSON *ExportConfig `yaml:"json"`
	} `yaml:"exports"`
}
type ExportConfig struct {
	Enable   bool   `yaml:"enable"`
	SavePath string `yaml:"savePath"`
	Header   string `yaml:"header"`
	// 在init 中进行关联
	DefConfig *DefaultConfig
}

func (c *Config) Init(configFilePath string) *Config {
	yamlFile, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		log.Printf("yamlFile.Get err   #%v ", err)
	}
	err = yaml.Unmarshal(yamlFile, c)
	if err != nil {
		log.Fatalf("Unmarshal: %v", err)
	}

	exportVal := reflect.ValueOf(c.Exports)
	refType := reflect.TypeOf(c.Exports)
	for i := 0; i < exportVal.NumField(); i++ {
		fieldVal := exportVal.Field(i)
		fieldType := refType.Field(i)
		if fieldVal.IsNil() {
			continue
		}
		exportConfig, ok := fieldVal.Interface().(*ExportConfig)
		if ok {
			exportConfig.DefConfig = GetDefConfig(fieldType.Name)
		}
	}
	return c
}
func (c *Config) getEnableConfig() map[string]*ExportConfig {
	exports := c.Exports
	var configs = make(map[string]*ExportConfig)

	exportVal := reflect.ValueOf(exports)
	refType := reflect.TypeOf(exports)
	for i := 0; i < exportVal.NumField(); i++ {
		fieldVal := exportVal.Field(i)
		fieldType := refType.Field(i)
		if fieldVal.IsNil() {
			continue
		}
		if fieldVal.Kind() == reflect.Ptr {
			fieldVal = fieldVal.Elem()
		}
		exportConfig, ok := fieldVal.Interface().(ExportConfig)
		if ok && exportConfig.Enable {
			configs[fieldType.Name] = &exportConfig
		}
	}
	return configs
}

type DefaultConfig struct {
	HeadFix  [2]string
	Builder  ExportBuilder
	FileFix  string
	WriteBOM bool
}

func NewDefaultConfig(headFix [2]string, builder ExportBuilder, fileFix string, writeBOM bool) *DefaultConfig {
	return &DefaultConfig{HeadFix: headFix, Builder: builder, FileFix: fileFix, WriteBOM: writeBOM}
}
